import buildQueryString from '@/utils/buildQueryString';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { dyCpsSearch } from './service';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [dateRange, setDateRange] = useState<any>();
  const [pageIndex, setPageIndex] = useState<string>('');
  const [timeType, setTimeType] = useState<any>(3);
  const [promotionType, setPromotionType] = useState<any>(0);
  const [count, setCount] = useState<number>(0);
  const [amount, setAmount] = useState<number>(0);
  const [proAmount, setProAmount] = useState<number>(0);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const orderStatuses = [
    {
      label: '创建',
      value: 0,
    },
    {
      label: '支付',
      value: 10,
    },
    {
      label: '退款',
      value: 20,
    },
    {
      label: '部分退款',
      value: 21,
    },
    {
      label: '结算',
      value: 30,
    },
    {
      label: '确认收货',
      value: 40,
    },
  ];
  const promotionTypes = [
    {
      label: '商品券',
      value: 0,
    },
    {
      label: '店铺券',
      value: 1,
    },
    {
      label: '活动券',
      value: 2,
    },
  ];
  const timeTypes = [
    {
      label: '订单创建时间',
      value: 1,
    },
    {
      label: '订单更新时间',
      value: 2,
    },
    {
      label: '订单支付时间',
      value: 3,
    },
  ];
  const distributionTypes = [
    {
      label: '未知',
      value: 0,
    },
    {
      label: '商品',
      value: 1,
    },
    {
      label: '直播间',
      value: 2,
    },
    {
      label: '活动页',
      value: 3,
    },
    {
      label: '本地生活服务',
      value: 4,
    },
  ];
  const cpsConf = [
    {
      label: 'YF_2',
      value: 'cps_zbj_yf2',
    },
    {
      label: 'YF_3',
      value: 'cps_zbj_yf3',
    },
    {
      label: 'YF_4',
      value: 'cps_zbj_yf4',
    },
    {
      label: 'YF_5',
      value: 'cps_zbj_yf5',
    },
    {
      label: 'YF_6',
      value: 'cps_zbj_yf6',
    },
    {
      label: 'YF_7',
      value: 'cps_zbj_yf7',
    },
    {
      label: 'APP_2',
      value: 'CPS-ZBJ-yf2',
    },
    {
      label: 'APP_3',
      value: 'CPS-ZBJ-yf3',
    },
    {
      label: 'APP_4',
      value: 'CPS-ZBJ-yf4',
    },
    {
      label: 'APP_5',
      value: 'CPS-ZBJ-yf5',
    },
    {
      label: 'APP_6',
      value: 'CPS-ZBJ-yf6',
    },
    {
      label: 'APP_7',
      value: 'CPS-ZBJ-yf7',
    },
  ];
  const columns: ProColumns<any>[] = [
    {
      title: '媒体APP',
      dataIndex: 'cps',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return cpsConf;
      },
    },
    {
      title: '订单查询时间类型',
      dataIndex: 'timeType',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return timeTypes;
      },
      fieldProps: {
        value: timeType,
        onChange: (val) => {
          setTimeType(val);
        },
      },
    },
    {
      title: '优惠券类型',
      dataIndex: 'promotionType',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return promotionTypes;
      },
      fieldProps: {
        value: promotionType,
        onChange: (val) => {
          setPromotionType(val);
        },
      },
    },
    {
      title: '店铺信息',
      dataIndex: 'storeName',
      copyable: true,
    },
    {
      title: '订单id',
      dataIndex: 'orderId',
      copyable: true,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      valueType: 'select',
      request: async () => {
        return orderStatuses;
      },
    },
    {
      title: '下单件数',
      dataIndex: 'items',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.items[0].itemNum;
      },
    },
    {
      title: '总付款金额',
      dataIndex: 'totalPayAmount',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.totalPayAmount / 100;
      },
    },
    {
      title: '预估结算金额',
      dataIndex: 'estimateSettlementAmount',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.estimateSettlementAmount / 100;
      },
    },
    {
      title: '预估佣金比例',
      dataIndex: 'estimateCmmRate',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.estimateCmmRate / 100 + '%';
      },
    },
    {
      title: '预估佣金金额',
      dataIndex: 'estimateCmmAmount',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.estimateCmmAmount / 100;
      },
    },
    {
      title: '推广费率',
      dataIndex: 'promotionFeeRate',
      hideInSearch: true,
    },
    {
      title: '预估技术服务费',
      dataIndex: 'estimateServiceFee',
      hideInSearch: true,
      render: (_, recod) => {
        return recod.estimateServiceFee / 100;
      },
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '产品',
      dataIndex: 'itemName',
      hideInSearch: true,
    },
    {
      title: '产品ID',
      dataIndex: 'itemId',
      copyable: true,
    },
    {
      title: '退款时间',
      dataIndex: 'refundTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '结算时间',
      dataIndex: 'settlementTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '收货时间',
      dataIndex: 'receivingTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单创建时间',
      dataIndex: 'orderCreateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单更新时间',
      dataIndex: 'orderUpdateTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '分销类型',
      dataIndex: 'distributionType',
      valueType: 'select',
      hideInSearch: true,
      request: () => {
        return distributionTypes;
      },
    },
    {
      title: '订单创建时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTimne: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value: any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
  ];
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    const endOfDay = new Date(new Date()).setHours(23, 59, 59, 0);
    setDateRange([startOfDay, endOfDay]);
  }, []);

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={
          '全部订单: / 总支付金额：' +
          count +
          '/ 总佣金：' +
          amount +
          '/ 渠道预估佣金：' +
          proAmount
        }
        actionRef={actionRef}
        rowKey="key"
        scroll={{ x: '1000px' }}
        search={{
          defaultCollapsed: false,
          labelWidth: 120,
          optionRender: ({ searchText, resetText }, { form }) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
              <Button
                key="export"
                type="primary"
                onClick={() => {
                  const defaultValues = columns.reduce((acc: any, column: any) => {
                    if (column.fieldProps && column.fieldProps.value !== undefined) {
                      acc[column.dataIndex] = column.fieldProps.value;
                    }
                    return acc;
                  }, {});

                  const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
                  const endTimne = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
                    'YYYY-MM-DD HH:mm:ss',
                  );
                  const fieldData = form.getFieldsValue();
                  let params = {
                    ...defaultValues,
                    startTime,
                    endTimne,
                    excelType: 'cps',
                  };
                  if (fieldData && fieldData.orderStatus !== undefined) {
                    params = { ...params, orderStatus: fieldData.orderStatus };
                  }
                  if (fieldData && fieldData.itemId !== undefined) {
                    params = { ...params, itemId: fieldData.itemId };
                  }
                  if (fieldData && fieldData.storeName !== undefined) {
                    params = { ...params, storeName: fieldData.storeName };
                  }
                  let str = buildQueryString(params);
                  window.open('/api/exportDyFile' + str);
                  console.log(str);
                }}
              >
                导出
              </Button>,
            ];
          },
        }}
        request={async (params: any) => {
          const defaultValues = columns.reduce((acc: any, column: any) => {
            if (column.fieldProps && column.fieldProps.value !== undefined) {
              acc[column.dataIndex] = column.fieldProps.value;
            }
            return acc;
          }, {});

          const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
          const endTimne = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
            'YYYY-MM-DD HH:mm:ss',
          );

          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTimne, pageIndex };

          const rsp = await dyCpsSearch(data);
          if (rsp.code === 'SUCCESS') {
            if (rsp.data.hasNext) {
              setPageIndex(rsp.data.pageIndex);
            }
            setCount(rsp.data.count);
            setAmount(rsp.data.amount);
            setProAmount(rsp.data.proAmount);
            return {
              data: rsp.data.list,
              total: rsp.data.list.length,
            };
          }
        }}
        pagination={{
          pageSize: 100,
        }}
        columns={columns}
      />
    </PageContainer>
  );
};
export default TableList;
